package servlets;

import db.ExpenseDAO;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/ApproveExpenseServlet")
public class ApproveExpenseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("employeeID") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        // 检查用户角色是否有审批权限
        String position = (String) session.getAttribute("position");
        if (!"财务".equals(position)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "您没有权限执行此操作");
            return;
        }

        // 获取当前登录员工ID作为审核人
        int approverId = (Integer) session.getAttribute("employeeID");

        int expenseId = Integer.parseInt(request.getParameter("id"));
        String action = request.getParameter("action");

        ExpenseDAO dao = new ExpenseDAO();
        try {
            boolean success;
            if ("approve".equals(action)) {
                success = dao.updateExpenseStatus(expenseId, approverId);
            } else {
                // 拒绝操作可能需要额外的处理
                success = true; // 根据实际需求修改
            }

            if (success) {
                response.sendRedirect("viewExpense.jsp?id=" + expenseId);
            } else {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "更新状态失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库错误: " + e.getMessage());
        }
    }
}